package net.yunxinyong.sign.service.impl;

import net.yunxinyong.sign.aop.CECException;
import net.yunxinyong.sign.entity.*;
import net.yunxinyong.sign.mapper.CecBaseMapper;
import net.yunxinyong.sign.mapper.CecSixMapper;
import net.yunxinyong.sign.mapper.EcnomicInventoryMapper;
import net.yunxinyong.sign.service.CecBaseService;
import net.yunxinyong.sign.service.CecOneService;
import net.yunxinyong.sign.service.CecSixSerivce;
import net.yunxinyong.sign.service.RecordService;
import net.yunxinyong.sign.utils.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
public class CecSixSerivceImpl implements CecSixSerivce {
    @Autowired
    private CecSixMapper cecSixMapper;
    @Autowired
    private RecordService recordService;
    @Autowired
    private CecBaseMapper cecBaseMapper;
    @Autowired
    private CecOneService cecOneService;
    @Autowired
    private CecBaseService cecBaseService;
    @Autowired
    private EcnomicInventoryMapper ecnomicInventoryMapper;
    @Override
    public CecSix select(int invid) {
        CecSixExample cecSixExample = new CecSixExample();
        //id和企业状态为正常作为查询条件
        cecSixExample.createCriteria().andInvIdEqualTo(invid).andStatusEqualTo(0);
        List<CecSix> list = cecSixMapper.selectByExample(cecSixExample);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void update(CecSix cecSix, Integer adminId) {
        cecSix.setUpdateTime(new Date());
        //base表（611表）和6表的标间关系
        Integer update = baseAndSixLogic1(cecSix);
        //1表和611表的表间关系
        sixAndOneLogic(cecSix);
        int count = cecSixMapper.updateByPrimaryKey(cecSix);
        boolean insert = recordService.insert(adminId, cecSix.getInvId(), null, 12);
        if (count <= 0 || !insert || update <=0) {
            throw new CECException(501, "更新失败!");
        }
        System.out.println("更新成功!");
    }

    @Override
    public void insert(CecSix cecSix, Integer adminId) {
        cecSix.setUpdateTime(new Date());
        cecSix.setCreateTime(new Date());
        cecSix.setStatus(0);
        //base表（611表）和6表的标间关系
        Integer update = baseAndSixLogic1(cecSix);
        //1表和611表的表间关系
        sixAndOneLogic(cecSix);
        int count = cecSixMapper.insert(cecSix);
        boolean insert = recordService.insert(adminId, cecSix.getInvId(), null, 12);
        if (count <= 0||!insert || update <=0) {
            throw new CECException(501, "添加失败!");
        }
        System.out.println("添加成功!");
    }

    public Integer baseAndSixLogic1(CecSix cecSix){
        CecBase cecBase = cecBaseService.select(cecSix.getInvId());
        if (cecBase != null){
            //往6表添加数据的时候，同时往base表194项添加数据
            //base 表数据
            // `non_unit_expenditure` decimal(20,5) DEFAULT NULL COMMENT '(194)非企业法人单位支出(单位：千元)',
            //  `non_unit_total_assets` decimal(20,5) DEFAULT NULL COMMENT '(194)非企业法人单位资产总计(单位：千元)',
            //6表数据
            //total_expenditure` decimal(20,2) DEFAULT NULL COMMENT '(18)本年费用合计 千元',
            //`total_assets` decimal(20,2) DEFAULT NULL COMMENT '(12)资产总计 '
            cecBase.setNonUnitExpenditure(cecSix.getTotalExpenditure());
            cecBase.setNonUnitTotalAssets(cecSix.getTotalAssets());
            return cecBaseMapper.updateByPrimaryKeySelective(cecBase);
        }else {
            throw new CECException(501,"请先填写611表");
        }
    }
    /**
     *  611-1 表和611-6表 表间逻辑。611-1表产业收入之和（支出）>=法人财务数据，不大于10%（611-1表 12项非经营性单位支出 > 611-6表 18项本年费用合计，且不大于18项本年费用合计的10%）
     * @param cecSix
     */
    public void sixAndOneLogic(CecSix cecSix){
        EcnomicInventoryExample ecnomicInventoryExample = new EcnomicInventoryExample();
        ecnomicInventoryExample.createCriteria().andIdEqualTo((long)cecSix.getInvId());
        List<EcnomicInventory> ecnomicInventories = ecnomicInventoryMapper.selectByExample(ecnomicInventoryExample);
        if (!ListUtils.isEmpty(ecnomicInventories)){
            EcnomicInventory ecnomicInventory = ecnomicInventories.get(0);
            //只有底册中type包含1 表时，才进行和1表的逻辑审核    这样做视为了防止 企业在 提交base表 之后 填写了部分的表 重新修改表类型，这时新分配的表是不包含 1表的。
            if (ecnomicInventory.getType() != null && ecnomicInventory.getType().contains("1")){
                List<CecOne> cecOneList = cecOneService.get(cecSix.getInvId());
                if (!ListUtils.isEmpty(cecOneList)){
                    BigDecimal oneNonBussineseIncome = new BigDecimal(0);
                    for (CecOne cecOne : cecOneList){
                        if (cecOne.getNonBussineseIncome() != null && !cecOne.getNonBussineseIncome().equals("")){
                            oneNonBussineseIncome = oneNonBussineseIncome.add(new BigDecimal(cecOne.getNonBussineseIncome()));
                        }
                    }
                    //611-1表 12项非经营性单位支出 > 611-6表 18项本年费用合计，且不大于18项本年费用合计的10%
                    BigDecimal totalExpenditure = cecSix.getTotalExpenditure();
                    boolean logic = !(totalExpenditure!= null && oneNonBussineseIncome.compareTo(totalExpenditure) >= 0) || !(totalExpenditure != null && totalExpenditure.multiply(new BigDecimal(1.1)).compareTo(oneNonBussineseIncome) >= 0 );
                    if (logic){
                        throw new CECException(502,"611-1表 12项非经营性单位支出 > 611-6表 18项本年费用合计，且不大于18项本年费用合计的10%");
                    }
                }
            }
        }

    }

}
